package com.nowcoder.community.config;

import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

// security配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略掉对静态资源的拦截
        web.ignoring().antMatchers("/resources/**"); // 所有resources下的静态资源都可以被忽略
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 授权配置
        http.authorizeRequests() // 允许基于使用HttpServletRequest限制访问
                .antMatchers(
                      "/user/setting",
                      "/user/upload",
                      "/discuss/add",
                      "/comment/add/**",
                      "/letter/**",
                      "/notice/**",
                      "/like",
                      "/follow",
                      "/unfollow"
                )
                .hasAnyAuthority(
                       AUTHORITY_USER, AUTHORITY_ADMIN, AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/top","/discuss/wonderful"
                )
                .hasAnyAuthority(
                        AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/delete", "/data/**","/actuator/**"
                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN
                )
                .anyRequest().permitAll() // 除了上述请求需要权限，其他任何请求都可以访问
                .and().csrf().disable(); // 不会生成csrf凭证了
        // 权限不够时的处理
        http.exceptionHandling() // 允许配置错误处理
                .authenticationEntryPoint(new AuthenticationEntryPoint() { // 没有登陆时怎么处理
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                        // 判断请求是同步的还是异步的
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if("XMLHttpRequest".equals(xRequestedWith)){
                            // 异步请求需要响应一个json字符串
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter(); // 获取字符流向前台输出内容
                            writer.write(CommunityUtil.getJSONString(403, "你还没有登陆"));
                        }else{
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() { // 登录了权限不足怎么处理
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
                        // 判断请求是同步的还是异步的
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if("XMLHttpRequest".equals(xRequestedWith)){
                            // 异步请求需要响应一个json字符串
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter(); // 获取字符流向前台输出内容
                            writer.write(CommunityUtil.getJSONString(403, "你没有访问此功能的权限"));
                        }else{
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });

        // security底层默认拦截/logout请求，进行退出处理
        // 若是使用security自带的退出管理，filter会在controller前自动拦截logout
        // 如果我们想用自己写的logout，覆盖他默认的逻辑，才能执行我们的代码
        http.logout().logoutUrl("/securitylogout"); // 将他的默认拦截路径进行修改，修编写一个我们不会用到的路径
    }
}

